package hu.myai.util.pool;

import hu.myai.model.TrendLineVO;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TrendLinePool {

	/**
	 * The object used when logging debug,errors,warnings and info.
	 * */
	private static Logger log = LoggerFactory.getLogger("IndicatorPool");

	/**
	 * the indicator pool grouped by tick
	 * */
	private Map<String, List<TrendLineVO>> pool = new HashMap<String, List<TrendLineVO>>();

	private static TrendLinePool resistance;

	private static TrendLinePool support;

	/**
	 * resistance line singleton
	 * */
	public synchronized static TrendLinePool getResistanceInstance() {
		if (resistance == null) {
			resistance = new TrendLinePool();
		}
		return resistance;
	}

	/**
	 * support line singleton
	 * */
	public synchronized static TrendLinePool getSupportInstance() {
		if (support == null) {
			support = new TrendLinePool();
		}
		return support;
	}

	/**
	 * add line to the tick specific pool
	 * */
	public Double addLine(TrendLineVO line, String tickName) {

		// get the appropriate pool if more than one available
		List<TrendLineVO> trendList = getLineList(tickName);

		if(!trendList.contains(line)){
			trendList.add(0, line);
			poolManintanance(tickName);
		}else{
			log.debug("Line is already in the list. " + line.toString());
		}

		return new Double(line.hashCode());
	}

	/**
	 * remove line from the tick specific pool
	 * */
	public boolean removeLine(TrendLineVO line, String tickName) {

		// get the appropriate pool if more than one available
		List<TrendLineVO> trendMap = getLineList(tickName);

		// check the indication if in the pool or need to add
		if (trendMap.contains(line)) {
			trendMap.remove(line);
			return true;
		} else {
			log.debug("Line is not in the list. " + line.toString());
		}
		return false;
	}

	/**
	 * get line from the tick specific pool
	 * */
	public TrendLineVO getLine(double hash, String tickName) {
		for (TrendLineVO line : getLineList(tickName)) {
			if (line.hashCode() == hash)
				return line;
		}
		return null;
	}

	/**
	 * reset the tick specific pool
	 * */
	public void reset(String tick) {
		pool.get(tick).clear();
	}

	/**
	 * Get the tick specified support group. If no tick specified support group
	 * than creates it.
	 * */
	public List<TrendLineVO> getLineList(String tickName) {

		// check the tick if in the pool or need to register
		if (pool.containsKey(tickName)) {
			return pool.get(tickName);
		} else {
			List<TrendLineVO> newLineList = new ArrayList<TrendLineVO>();
			pool.put(tickName, newLineList);
			return newLineList;
		}
	}

	/**
	 * maintain the size of the pool size
	 * */
	private void poolManintanance(String tickName) {
		while (pool.get(tickName).size() > 200)
			pool.get(tickName).remove(pool.get(tickName).size() - 1);
	}
}
